<template>
	<view class="cg-custom-loading">
		<view class="loading-mask" v-if="loading">
			<view class="loading-content">
				<view class="loading-spinner"></view>
				<text class="loading-text">{{config.message}}</text>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		eventBus
	} from '@/common/utils/eventBus';
	export default {
		data() {
			return {
				loading: false,
				config: {}
			}
		},
		methods: {
			openLoading(config) {
				this.loading = true;
				if (config.duration) {
					setTimeout(() => {
						this.loading = false;
					}, config.duration);

				}
			},
			closeLoading(config) {
				setTimeout(() => {
					this.loading = false;
				}, config.timeout);
			}
		},
		mounted() {

			// #ifdef H5
			this.route = this.$parent.$route.meta.pagePath;

			eventBus.$on(`openCustomLoading${this.route}`, (route, config) => {
				this.config = config;
				this.openLoading(config);
			})
			eventBus.$on(`closeCustomLoading${this.route}`, (route, config) => {
				this.closeLoading(config)
			})
			// #endif

			// #ifndef H5
			if (this.$parent.$mp && !this.$parent?.$mp?.page) {
				console.error(
					'unknow page, please check,this compnents needs a page as a parent,can not used in another component'
				)
				return
			}
			this.route = this.$parent?.$mp.page.route;
			eventBus.$on(`openCustomLoading${this.route}`, (route, config) => {
				this.config = config;
				this.openLoading(config)
			})
			eventBus.$on(`closeCustomLoading${this.route}`, (route, config) => {
				this.closeLoading(config)
			})
			// #endif

		},

		beforeDestroy() {
			eventBus.$off(`customLoading${this.route}`)
			console.log('已销毁监听，避免内存泄漏', );
		},

	}
</script>

<style lang="scss" scoped>
	.loading-mask {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.5);
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 9999;
	}

	.loading-content {
		display: flex;
		flex-direction: column;
		align-items: center;
		background-color: #ffffff;
		padding: 40rpx;
		border-radius: 16rpx;
	}

	.loading-spinner {
		width: 60rpx;
		height: 60rpx;
		border: 6rpx solid #f3f3f3;
		border-top: 6rpx solid $mainColor;
		border-radius: 50%;
		animation: spin 1s linear infinite;
		margin-bottom: 20rpx;
	}

	@keyframes spin {
		0% {
			transform: rotate(0deg);
		}

		100% {
			transform: rotate(360deg);
		}
	}

	.loading-text {
		font-size: 28rpx;
		color: #333333;
	}
</style>